import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { ApplyFriendDTO } from '@modules/friend/dto/index';
import { AuthService } from '@auth/index';
import { FriendApplyEntity } from '@modules/friend/entity/friend.apply.entity';
import { FriendEntity } from '@modules/friend/entity/friend.entity';
import { UserEntity } from '@modules/user/entity/user.entity';

@Injectable()
export class FriendService {
  constructor(
    private readonly authService: AuthService,
    @InjectRepository(FriendApplyEntity)
    private readonly friendApplyRepository: Repository<FriendApplyEntity>,
    @InjectRepository(FriendEntity)
    private readonly friendRepository: Repository<FriendEntity>,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  /**
   * 申请添加好友
   */
  async applyFriend(body: ApplyFriendDTO) {
    const { userId, userName, userUrl, friendId, friendName, friendUrl, msg } = body;
    if (body.friendId === body.userId) {
      return { code: 500, msg: '自己不能申请添加好友' };
    }
    const params = { userId, userName, userUrl, friendId, friendName, friendUrl, msg, status: 2 };
    await this.friendApplyRepository.save(params);
    return { code: 200, msg: '申请成功', data: params };
  }

  /**
   * 获取申请好友列表
   */
  async getApplyFriendList(token: string) {
    const tokenResult = await this.authService.getTokenUser(token);
    const result = await this.friendApplyRepository.find({
      where: [{ userId: tokenResult.userId }, { friendId: tokenResult.userId }],
      order: { id: 'ASC' },
    });
    console.log('获取申请好友列表', result);
    const formatData = result.map((item) => {
      if (Number(item.userId) === Number(tokenResult.userId)) {
        // 申请方
        return {
          userId: item.friendId,
          username: item.friendName,
          imgUrl: item.friendUrl,
          msg: item.msg,
          status: item.status,
          type: 1, // 1 申请方 2接受方
        };
      } else {
        // 接受方
        return {
          userId: item.userId,
          username: item.userName,
          imgUrl: item.userUrl,
          msg: item.msg,
          status: item.status,
          type: 2, // 1 申请方 2接受方
        };
      }
    });
    // console.log('tokenResult', tokenResult);
    return { code: 200, msg: '获取申请好友列表', data: formatData };
  }

  /**
   * 更新好友状态
   */
  async updateFriendStatus(token: string, body: ApplyFriendDTO) {
    const tokenResult = await this.authService.getTokenUser(token);
    console.log('tokenResult', tokenResult);
    if (Number(body.status) === 1) {
      console.log('好友', body.status);
      this.friendRepository.save({ userId: tokenResult.userId, friendId: body.friendId });
    }
    await this.friendApplyRepository
      .createQueryBuilder()
      .update()
      .set({ status: body.status })
      .where({ friendId: tokenResult.userId, status: 2 })
      .execute();
    return { code: 200, msg: '更新好友状态' };
  }

  /**
   * 获取好友列表
   */
  async getFriendList(token: string) {
    const tokenResult = await this.authService.getTokenUser(token);
    const userId = tokenResult.userId;
    console.log('tokenResult', tokenResult);
    const friendResult = await this.friendRepository.find({ where: [{ userId }, { friendId: userId }] });
    const findArrData = [];
    friendResult.forEach((item) => {
      findArrData.push(item.userId);
      findArrData.push(item.friendId);
    });
    const userResult = await this.userRepository.find({
      where: { userId: In(findArrData) },
      select: ['userId', 'username', 'imgUrl', 'desc'],
    });
    const result = userResult.map((item) => {
      if (Number(item.userId) === Number(userId)) {
        return { ...item, type: 1 };
      }
      return { ...item, type: 2 };
    });
    return { code: 200, msg: '获取好友列表', data: result };
  }

  /**
   * 获取好友详情
   */
  async getFriendDetails(id: number) {
    const { password, ...arg } = await this.userRepository.findOne({ where: { userId: id } });
    return { code: 200, msg: '获取好友详情', data: arg };
  }

  /**
   * 删除好友
   */
  async deleteFriend(token, id: number) {
    const tokenResult = await this.authService.getTokenUser(token);

    await this.friendRepository
      .createQueryBuilder()
      .delete()
      .where([
        { friendId: id, userId: tokenResult.userId },
        { friendId: tokenResult.userId, userId: id },
      ])
      .execute();

    return { code: 200, msg: '删除好友成功' };
  }
}
